import { sendError } from "h3";
import fs from "fs";
import path from "path";

export default defineEventHandler(async (event) => {
  // 获取请求体数据
  const body = await readBody(event);

  // 验证请求数据
  if (!body || !body.filename) {
    return sendError(
      event,
      createError({
        statusCode: 400,
        statusMessage: "缺少文件名",
      })
    );
  }

  // 构建文件路径
  const uploadDir = path.join(process.cwd(), "public", "uploads");
  const filePath = path.join(uploadDir, body.filename);

  try {
    // 检查文件是否存在
    if (!fs.existsSync(filePath)) {
      return sendError(
        event,
        createError({
          statusCode: 404,
          statusMessage: "图片文件不存在",
        })
      );
    }

    // 删除文件
    fs.unlinkSync(filePath);

    return {
      success: true,
      message: "图片删除成功",
      filename: body.filename,
    };
  } catch (error) {
    return sendError(
      event,
      createError({
        statusCode: 500,
        statusMessage: "删除文件失败",
      })
    );
  }
});
